package com.bckj.fastboot.iot.biz.service.impl;

import com.bckj.fastboot.core.extra.cache.CacheOps;
import com.bckj.fastboot.iot.biz.convert.IotAlarmRuleConvert;
import com.bckj.fastboot.iot.biz.repository.IotAlarmRuleRepository;
import com.bckj.fastboot.iot.biz.service.IotAlarmRuleService;
import com.bckj.fastboot.iot.common.constant.IotCacheConstants;
import com.bckj.fastboot.iot.common.dto.request.IotAlarmRuleRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * IotAlarmRuleServiceImpl
 *
 * @author wfc
 **/
@Service
@RequiredArgsConstructor
public class IotAlarmRuleServiceImpl implements IotAlarmRuleService {

    private final CacheOps cacheOps;
    private final IotAlarmRuleConvert iotAlarmRuleConvert;
    private final IotAlarmRuleRepository iotAlarmRuleRepository;

    @Override
    public boolean save(IotAlarmRuleRequest request) {
        var entity = iotAlarmRuleConvert.toEntity(request);
        return iotAlarmRuleRepository.save(entity);
    }

    @Override
    public boolean update(IotAlarmRuleRequest request) {
        var entity = iotAlarmRuleConvert.toEntity(request);
        return iotAlarmRuleRepository.updateById(entity);
    }

    @Override
    public boolean remove(Long id) {
        return iotAlarmRuleRepository.removeById(id);
    }

    @Override
    public void clearRulesCache(String protocolCode, String[] cmdArr) {
        Assert.notNull(protocolCode, "protocolCode can not be null");
        var cache = cacheOps.redisCache(IotCacheConstants.IOT_ALARM_RULE_KEY_PREFIX);
        if (cmdArr == null || cmdArr.length == 0) {
            cache.evict(protocolCode);
        } else {
            for (String cmd : cmdArr) {
                cache.evict(protocolCode + cmd);
            }
        }
    }

}
